import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

///防止多次点击的控件
// ignore: must_be_immutable
class Click extends StatelessWidget {
  final Widget child;
  final Function? onTap;
  final Function? onLongPress;
  final Color? color;

  // final String? bgImage;
  // final String? bgPressImage;

  //是否需要点击的波动动画，默认true，只对false进行特殊处理
  final bool hasWave;

  Click(
      {required this.child,
      this.onTap,
      this.onLongPress,
      this.color,
      this.hasWave = true,Key? key}): super(key: key);

  bool _click = false;

  @override
  Widget build(BuildContext context) {
    return !hasWave ? _noWaveView() : _hasWaveView();
  }

  ///使用InkWell自带的波纹点击效果
  Widget _hasWaveView() {
    return Material(
      color: this.color == null ? Color(0x00000000) : this.color,
      child: InkWell(
        child: this.child,
        onTap: this.onTap == null ? null : _onTap,
        onLongPress: () {
          this.onLongPress?.call();
        },
      ),
    );
  }

  ///无波纹点击效果
  Widget _noWaveView() {
    return GestureDetector(
      onTap: _onTap,
      onTapDown: (detail) {
        this._click = true;
      },
      onTapCancel: () {
        this._click = false;
      },
      onTapUp: (detail) {
        this._click = false;
      },
      child: child,
    );
  }

  ///点击
  _onTap() async {
    if (_click) {
      return;
    }
    _click = true;
    await onTap?.call();
    //多等待
    Future.delayed(const Duration(milliseconds: 500), () {
      _click = false;
    });
  }
}

/// 防抖
VoidCallback debounceCB(VoidCallback fn, [int t = 500]) {
  Timer? _debounce;
  return () {
    // 还在时间之内，抛弃上一次
    if (_debounce?.isActive ?? false) _debounce?.cancel();

    _debounce = Timer(Duration(milliseconds: t), () {
      fn();
    });
  };
}

Function debounceFn(Function fn, [int t = 500]) {
  Timer? _debounce;
  return () {
    // 还在时间之内，抛弃上一次
    if (_debounce?.isActive ?? false) _debounce?.cancel();

    _debounce = Timer(Duration(milliseconds: t), () {
      fn();
    });
  };
}
